package com.real.operationalcontrols.任务;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.elvishew.xlog.XLog;
import com.google.gson.Gson;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions;
import com.nanchen.compresshelper.CompressHelper;
import com.real.operationalcontrols.R;
import com.real.operationalcontrols.rxhttp.MyDialogObserver;
import com.real.operationalcontrols.rxhttp.NetworkUrl;
import com.real.operationalcontrols.rxhttp.RxHttpManger;
import com.real.operationalcontrols.基类.BaseActivity;
import com.real.operationalcontrols.实体类.LoginBean;
import com.real.operationalcontrols.实体类.TaskDetialBean;
import com.real.operationalcontrols.工具包.DeleteItemListener;
import com.real.operationalcontrols.工具包.GridSpacingItemDecoration;
import com.real.operationalcontrols.适配器.PhotoOneAdapter;
import com.real.operationalcontrols.适配器.PhotoTwoAdapter;
import com.real.operationalcontrols.适配器.TaskDataAdapter;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.common.ImageLoader;
import com.yuyh.library.imgsel.config.ISListConfig;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
import rxhttp.wrapper.entity.UpFile;

@RuntimePermissions
public class TaskInfoActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    @BindView(R.id.bar_back_btn)
    ImageView barBackBtn;
    @BindView(R.id.bar_title)
    TextView barTitle;
    @BindView(R.id.bar_check_btn)
    TextView barCheckBtn;
    @BindView(R.id.task_id)
    TextView taskId;
    @BindView(R.id.task_time)
    TextView taskTime;
    @BindView(R.id.task_name)
    TextView taskName;
    @BindView(R.id.task_location)
    TextView taskLocation;
    @BindView(R.id.paizhao_one_btn)
    ImageView paizhaoOneBtn;
    @BindView(R.id.rv_img_one)
    RecyclerView rvImgOne;
    @BindView(R.id.rv_task)
    RecyclerView rvTask;
    @BindView(R.id.paizhao_two_btn)
    ImageView paizhaoTwoBtn;
    @BindView(R.id.rv_img_two)
    RecyclerView rvImgTwo;
    @BindView(R.id.task_beizhu)
    EditText taskBeizhu;
    @BindView(R.id.task_btn)
    TextView taskBtn;
    @BindView(R.id.task_address)
    TextView taskAddress;
    @BindView(R.id.rg_yes)
    RadioButton rgYes;
    @BindView(R.id.rg_no)
    RadioButton rgNo;
    @BindView(R.id.rg)
    RadioGroup rg;
    int checkType;
    int isSend;
    String id;
    PhotoOneAdapter oneAdapter;
    PhotoTwoAdapter twoAdapter;
    TaskDataAdapter dataAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_task_info);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_task_info;
    }

    @Override
    protected void getData() {
        id = getIntent().getStringExtra("id");
        rg.setOnCheckedChangeListener(this);
        rgYes.setChecked(true);
        initAdapter();
        initData();
    }

    private void initData() {
        Map<String, String> map = new HashMap<>();
        map.put("taskname", id);
        RxHttpManger.getInstance().get(this, NetworkUrl.TASK_DETIAL, map,
                new MyDialogObserver(this) {
                    @Override
                    public void onSuccess(String response) {
                        TaskDetialBean bean = new Gson().fromJson(response, TaskDetialBean.class);
                        if (bean.isSuccess()) {
                            taskId.setText(bean.getTasklist().get(0).getId());
                            taskTime.setText(bean.getTasklist().get(0).getTime());
                            taskAddress.setText(bean.getTasklist().get(0).getAddress());
                            taskName.setText(bean.getTasklist().get(0).getPeople());
                            for (int i = 0; i < bean.getTasklist().get(0).getContext().size(); i++) {
                                taskData.add(bean.getTasklist().get(0).getContext().get(i).getTip());
                            }
                            dataAdapter.setData(taskData);
                        } else {
                            ToastUtils.showShort(bean.getMessage());
                        }
                    }
                });
    }

    @OnClick({R.id.bar_back_btn, R.id.bar_check_btn, R.id.paizhao_one_btn, R.id.paizhao_two_btn,
            R.id.task_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bar_back_btn:
                finish();
                break;
            case R.id.bar_check_btn:
                checkType = 0;
                TaskInfoActivityPermissionsDispatcher.callWithPermissionCheck(this);
                break;
            case R.id.paizhao_one_btn:
                checkType = 1;
                checkPhoto();
                break;
            case R.id.paizhao_two_btn:
                checkType = 2;
                checkPhoto();
                break;
            case R.id.task_btn:
                sendPicture(onePath);
                break;
        }
    }

    List<String> onePath = new ArrayList<>();
    List<String> twoPath = new ArrayList<>();
    List<String> taskData = new ArrayList<>();

    private void initAdapter() {
        oneAdapter = new PhotoOneAdapter(this);
        rvImgOne.setHasFixedSize(true);
        rvImgOne.setNestedScrollingEnabled(false);
        rvImgOne.setLayoutManager(new GridLayoutManager(this, 3));
        rvImgOne.addItemDecoration(new GridSpacingItemDecoration(3, 15, true));
        rvImgOne.setAdapter(oneAdapter);

        oneAdapter.setDeleteItemListener(new DeleteItemListener() {
            @Override
            public void setDeleteItemListener(int position) {
                onePath.remove(position);
                oneAdapter.notifyDataSetChanged();

            }
        });
        twoAdapter = new PhotoTwoAdapter(this);
        rvImgTwo.setHasFixedSize(true);
        rvImgTwo.setNestedScrollingEnabled(false);
        rvImgTwo.setLayoutManager(new GridLayoutManager(this, 3));
        rvImgTwo.addItemDecoration(new GridSpacingItemDecoration(3, 15, true));
        rvImgTwo.setAdapter(twoAdapter);

        twoAdapter.setDeleteItemListener(new DeleteItemListener() {
            @Override
            public void setDeleteItemListener(int position) {
                twoPath.remove(position);
                twoAdapter.notifyDataSetChanged();
            }
        });

        dataAdapter = new TaskDataAdapter(this);
        rvTask.setHasFixedSize(true);
        rvTask.setNestedScrollingEnabled(false);
        rvTask.setLayoutManager(new LinearLayoutManager(this));
        rvTask.setAdapter(dataAdapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        if (requestCode == 200 && checkType == 0) {
            HmsScan obj = data.getParcelableExtra(ScanUtil.RESULT);
            if (obj != null) {
                ToastUtils.showShort(obj.originalValue);
            }
        } else if (requestCode == 200 && checkType == 1) {
            onePath = data.getStringArrayListExtra("result");
            oneAdapter.setData(onePath);

        } else if (requestCode == 200 && checkType == 2) {
            twoPath = data.getStringArrayListExtra("result");
            twoAdapter.setData(twoPath);
        }
    }

    //上传图片
    private void sendPicture(List<String> onePath) {
        String log = taskBeizhu.getText().toString().trim();
        if (log.isEmpty()) {
            log = "";
        }
        if (onePath.isEmpty()) {
            ToastUtils.showShort("请上传故障报告采集");
            return;
        }
        List<UpFile> fileList = new ArrayList<>();
        for (int i = 0; i < onePath.size(); i++) {
            File oldFile = new File(onePath.get(i));
            File newFile = new CompressHelper.Builder(this).setCompressFormat(Bitmap.CompressFormat.PNG).build().compressToFile(oldFile);
            fileList.add(new UpFile("file" + i, newFile.getAbsolutePath()));
        }
        Map<String, String> map = new HashMap<>();
        map.put("taskname", id);
        map.put("Action", "h");
        map.put("tasktype", String.valueOf(isSend));
        map.put("tasklog", log);
        RxHttpManger.getInstance().upLoadFiles(this, NetworkUrl.TASK_PICTURE_BEFORE, map,
                fileList,
                new MyDialogObserver(this) {
                    @Override
                    public void onSuccess(String response) {
                        LoginBean bean = new Gson().fromJson(response, LoginBean.class);
                        if (bean.isSuccess()) {
                            ToastUtils.showShort("上传完成");
                            finish();
                        } else {
                            ToastUtils.showShort(bean.getMessage());
                        }
                    }
                });
    }

    private void checkPhoto() {
        // 自定义图片加载器
        ISNav.getInstance().init(new ImageLoader() {
            @Override
            public void displayImage(Context context, String path, ImageView imageView) {
                Glide.with(context).load(path).into(imageView);
            }
        });

        // 自由配置选项
        ISListConfig config = new ISListConfig.Builder()
                // 是否多选, 默认true
                .multiSelect(true)
                // 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
                .rememberSelected(false)
                // “确定”按钮背景色
                .btnBgColor(Color.WHITE)
                // “确定”按钮文字颜色
                .btnTextColor(Color.BLACK)
                // 使用沉浸式状态栏
                .statusBarColor(Color.parseColor("#1b74eb"))
                // 返回图标ResId
                .backResId(R.mipmap.title_bar_back_withe)
                // 标题
                .title("图片选择")
                // 标题文字颜色
                .titleColor(Color.WHITE)
                // TitleBar背景色
                .titleBgColor(Color.parseColor("#1b74eb"))
                // 裁剪大小。needCrop为true的时候配置
                // .cropSize(1, 1, 200, 200)
                .needCrop(false)
                // 第一个是否显示相机，默认true
                .needCamera(true)
                // 最大选择图片数量，默认9
                .maxNum(5)
                .build();
        // 跳转到图片选择器
        ISNav.getInstance().toListActivity(this, config, 200);
    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE})
    void call() {
        //同意之后的回调
        ScanUtil.startScan(this, 200,
                new HmsScanAnalyzerOptions.Creator().setHmsScanTypes(HmsScan.QRCODE_SCAN_TYPE).create());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        TaskInfoActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode,
                grantResults);
    }

    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE})
    void call2(final PermissionRequest request) {
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rg_yes:
                isSend = 1;
                XLog.i("是否上传" + isSend);
                break;
            case R.id.rg_no:
                isSend = 0;
                break;
            default:
                break;
        }
    }
}
